from typing import ByteString
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand 
from ability.models import Course, Chapter, Experiment, UserProfile
from os.path import dirname, isfile, join
from os import listdir
import json


class Command(BaseCommand):
  help = 'import experiment from oracle'

  def add_arguments(self, parser):
      parser.add_argument('dirs', type=str)

  def handle(self, *args, **options):
      print('handle import points', options['dirs'])
      pointdir = options['dirs']
      course_name = options['dirs'].split('/')[-1]
      print(course_name)
      course = Course.objects.filter(course_name=course_name).first()
      if course is None:
        print("course %s is not exists" % course_name )
      onlyfiles = sorted([f for f in listdir(pointdir) if isfile(join(pointdir, f))])
      print(onlyfiles)
      user = UserProfile.objects.filter(username="18611010126").first()
      teacher = user.teacher
      for f in onlyfiles:
        if f == '.DS_Store':
          continue
        file = join(pointdir, f)
        with open(file, 'r') as json_file:
          experiment = Experiment()
          experiment.describe = json_file.read()
          experiment.duration = 60
          experiment.detail_type = 'M'
          experiment.status = 'N'
          experiment.ending_time = "2022-04-29T16:00:00.000Z"
          experiment.experiment_name = course_name + '-' + f.replace('.md', '')
          experiment.save()
          experiment.teacher.add(teacher)
